package com.ruoyi.web.controller.index;/**
 * @author 🤙🤙🏼🤙🏽
 * @date 2025 9月 10 10:48
 * @Description
 */

import com.ruoyi.blindBoxManage.mapper.BlindBoxMapper;
import com.ruoyi.blindBoxManage.mapper.BlindBoxProductMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.vo.*;
import com.ruoyi.mall.mapper.OrderMapper;
import com.ruoyi.order.mapper.BlindBoxOrderMapper;
import com.ruoyi.userManage.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 🤙🤙🏼🤙🏽
 * @date 2024 9月 25 17:29
 * @Description
 */
@RestController
@RequestMapping("/index/index")
public class IndexController extends BaseController {
    @Resource
    private UserMapper userMapper;
    @Resource
    private BlindBoxOrderMapper blindBoxOrderMapper;
    @Resource
    private BlindBoxProductMapper blindBoxProductMapper;
    @Resource
    private BlindBoxMapper blindBoxMapper;
    @Resource
    private OrderMapper orderMapper;

    @GetMapping("topData")
    public AjaxResult topData() {
        IndexResponseBaseVo baseVo = new IndexResponseBaseVo();
        //计算销售额 销售额=盲盒支付金额 +背包支付运费
        //先查询今日销售额
        IndexIncomeData indexIncome = new IndexIncomeData();
        IndexIncomeData indexIncomeData = blindBoxOrderMapper.selectDayIncomeData();
        if (ObjectUtils.isEmpty(indexIncomeData)) {
            indexIncomeData.setDayPoint(3);
            indexIncomeData.setCurrentDayIncomeData(BigDecimal.ZERO);
            indexIncomeData.setBeforeDayIncomeData(BigDecimal.ZERO);
        } else {
            if (indexIncomeData.getCurrentDayIncomeData().compareTo(indexIncomeData.getBeforeDayIncomeData()) > 0) {
                indexIncomeData.setDayPoint(1);
            } else if (indexIncomeData.getCurrentDayIncomeData().compareTo(indexIncomeData.getBeforeDayIncomeData()) < 0) {
                indexIncomeData.setDayPoint(0);
            } else {
                indexIncomeData.setDayPoint(3);
            }
        }
        indexIncome.setDayPoint(indexIncomeData.getDayPoint());
        indexIncome.setCurrentDayIncomeData(indexIncomeData.getCurrentDayIncomeData());
        indexIncome.setBeforeDayIncomeData(indexIncomeData.getBeforeDayIncomeData());


        //先查询本月销售额
        IndexIncomeData indexIncomeMonthData = blindBoxOrderMapper.selectMonthIncomeData();
        if (ObjectUtils.isEmpty(indexIncomeMonthData)) {
            indexIncomeMonthData.setMonthPoint(3);
            indexIncomeMonthData.setCurrentMonthIncomeData(BigDecimal.ZERO);
            indexIncomeMonthData.setBeforeMonthIncomeData(BigDecimal.ZERO);
        } else {
            if (indexIncomeMonthData.getCurrentMonthIncomeData().compareTo(indexIncomeMonthData.getBeforeMonthIncomeData()) > 0) {
                indexIncomeMonthData.setMonthPoint(1);
            } else if (indexIncomeMonthData.getCurrentMonthIncomeData().compareTo(indexIncomeMonthData.getBeforeMonthIncomeData()) < 0) {
                indexIncomeMonthData.setMonthPoint(0);
            } else {
                indexIncomeMonthData.setMonthPoint(3);
            }
        }
        indexIncome.setMonthPoint(indexIncomeMonthData.getMonthPoint());
        indexIncome.setCurrentMonthIncomeData(indexIncomeMonthData.getCurrentMonthIncomeData());
        indexIncome.setBeforeMonthIncomeData(indexIncomeMonthData.getBeforeMonthIncomeData());
        baseVo.setIndexIncomeData(indexIncome);

        //计算毛利润 利润=销售额-盲盒商品价格
        //先计算盲盒商品价格
        IndexProfitData profitData = blindBoxProductMapper.selectProfitData();
        if (ObjectUtils.isEmpty(profitData)) {
            profitData.setPoint(3);
            profitData.setCurrentDayProfitData(BigDecimal.ZERO);
            profitData.setBeforeDayProfitData(BigDecimal.ZERO);
        } else {
            profitData.setCurrentDayProfitData(indexIncome.getCurrentDayIncomeData().subtract(profitData.getCurrentDayProfitData()));
            profitData.setBeforeDayProfitData(indexIncome.getBeforeDayIncomeData().subtract(profitData.getBeforeDayProfitData()));
            if (profitData.getCurrentDayProfitData().compareTo(profitData.getBeforeDayProfitData()) > 0) {
                profitData.setPoint(1);
            } else if (profitData.getCurrentDayProfitData().compareTo(profitData.getBeforeDayProfitData()) < 0) {
                profitData.setPoint(0);
            } else {
                profitData.setPoint(3);
            }
        }

        baseVo.setIndexProfitData(profitData);
        //查询用户数据

        IndexUserData indexUserData = userMapper.selectIndexUserData();
        if (indexUserData.getCurrentUserData() > indexUserData.getBeforeUserData()) {
            indexUserData.setPoint(1);
        } else if (indexUserData.getCurrentUserData() < indexUserData.getBeforeUserData()) {
            indexUserData.setPoint(0);
        } else {
            indexUserData.setPoint(3);
        }
        baseVo.setIndexUserData(indexUserData);
        return AjaxResult.success(baseVo);
    }

    @GetMapping("middleLeftData")
    public AjaxResult middleLeftData() {
        MiddleLeftDataResponseVo baseVo = new MiddleLeftDataResponseVo();
        //一番赏
        List<BarChat> firstPrizeList = batchQueryByTimeIntervals(1);
        //区间赏
        List<BarChat> rangPrizeList = batchQueryByTimeIntervals(2);
        //无限赏
        List<BarChat> limitPrizeList = batchQueryByTimeIntervals(3);
        baseVo.setFirstPrizeList(firstPrizeList);
        baseVo.setRangPrizeList(rangPrizeList);
        baseVo.setLimitPrizeList(limitPrizeList);
        return AjaxResult.success(baseVo);
    }

    //排序类型：1-用户量正序，2-用户量倒序，3-销售额正序，4-销售额倒序
    @GetMapping("middleRightData")
    public TableDataInfo middleRightData(@RequestParam Integer sort) {
        startPage();
        List<MiddleRightDataResponseVo> baseVo = blindBoxMapper.middleRightData(sort);
        if (!CollectionUtils.isEmpty(baseVo)) {
            Integer rank = 0;
            for (MiddleRightDataResponseVo middleRightDataResponseVo : baseVo) {
                rank++;
                middleRightDataResponseVo.setRank(rank);
                BigDecimal income = orderMapper.selectIncome(middleRightDataResponseVo.getBlindBoxId());
                middleRightDataResponseVo.setIncome(middleRightDataResponseVo.getIncome().add(income));
            }
        }
        return getDataTable(baseVo);
    }


    @GetMapping("bottomData")
    public AjaxResult bottomData() {
        MiddleLeftDataResponseVo baseVo = new MiddleLeftDataResponseVo();
        //查询该时段的所有数据
        //单独计算每一种玩法的数据
        //计算占比
        List<BarChat> total = batchQuery(0);
        //一番赏
        List<BarChat> firstPrizeList = batchQuery(1);
        //区间赏
        List<BarChat> rangPrizeList = batchQuery(2);
        //无限赏
        List<BarChat> limitPrizeList = batchQuery(3);
        calculateRate(total, firstPrizeList, rangPrizeList, limitPrizeList);
        baseVo.setFirstPrizeList(firstPrizeList);
        baseVo.setRangPrizeList(rangPrizeList);
        baseVo.setLimitPrizeList(limitPrizeList);

        return AjaxResult.success(baseVo);
    }

    private List<BarChat> batchQueryByTimeIntervals(Integer playTypeId) {
        // 2. 获取当前时间并计算24小时前的时间
        LocalDateTime start = LocalDateTime.now();
        List<String> intervals = DateUtils.generateTimeInterval( start, 1);
        List<BarChat> barChats = new ArrayList<>();

        for (int i = 1; i < intervals.size(); i++) {
            String intervalStart = intervals.get(i - 1);
            String intervalEnd = intervals.get(i);
            BigDecimal intervalData = blindBoxOrderMapper.selectIncomeByDateRang(intervalStart, intervalEnd, playTypeId);
            BarChat barChat = new BarChat();
            barChat.setDate(intervalEnd.substring(intervalEnd.indexOf(" ")));
            barChat.setIncome(intervalData);
            barChats.add(barChat);
        }
        return barChats;
    }

    private List<BarChat> batchQuery(Integer playTypeId) {
        // 2. 获取当前时间并计算24小时前的时间
        LocalDateTime start = LocalDateTime.now();
        List<String> intervals = DateUtils.generateTimeInterval( start, 1);

        List<BarChat> barChats = new ArrayList<>();

        for (int i = 1; i < intervals.size(); i++) {
            String intervalStart = intervals.get(i - 1);
            String intervalEnd = intervals.get(i);
            Integer count = blindBoxOrderMapper.selectCount(intervalStart, intervalEnd, playTypeId);
            BarChat barChat = new BarChat();
            barChat.setDate(intervalEnd.substring(intervalEnd.indexOf(" ")));
            barChat.setCount(count);
            barChats.add(barChat);
        }
        return barChats;
    }


    @SafeVarargs
    public static void calculateRate(List<BarChat> totalList, List<BarChat>... partialLists) {
        // 将总列表转换为按日期分组的映射表
        Map<String, Integer> totalCountByDate = totalList.stream()
                .collect(Collectors.toMap(
                        BarChat::getDate,
                        BarChat::getCount
                ));

        // 处理每个部分列表
        for (List<BarChat> partialList : partialLists) {
            for (BarChat item : partialList) {
                String date = item.getDate();
                Integer totalCount = totalCountByDate.get(date);

                if (totalCount != null && totalCount != 0) {
                    // 计算占比并转换为百分比（保留两位小数）
                    BigDecimal rate = new BigDecimal(item.getCount())
                            .multiply(new BigDecimal(100))
                            .divide(new BigDecimal(totalCount), 2, RoundingMode.HALF_UP);
                    item.setRate(rate);
                } else {
                    // 如果总数为0或找不到对应日期，占比设为0
                    item.setRate(BigDecimal.ZERO);
                }
            }
        }
    }
}
